package hiWorld.amad.it;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import com.google.android.maps.*;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends MapActivity {
	
	TextView myTextView;
	Button myButton;
	timerManager myTM;
	LocationManager locMan;
	
	gpsLog myGpsLog = new gpsLog();
	
	static dbHelper myDBHelper;
	static int myLong =(int)(41.0766522*1e6);
	static int myLat =(int)(14.3564367*1e6); 
	 public static final String startString = "it.amad.gpsLogger.letsStart";
	 
	 public static Context myContext;
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myContext = getApplicationContext();
        
        myDBHelper = new dbHelper(myContext);
        
        MapView myMapView = (MapView)findViewById(R.id.myMapView);
        MapController myMapCtrl = (MapController)myMapView.getController();
        
        myMapView.setSatellite(false);
        myMapView.setStreetView(false);

        MySettings.preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                
        myMapCtrl.setZoom(12);

        GeoPoint gp = new GeoPoint(myLong, myLat);
       
        myMapCtrl.setCenter(gp);

    }
    
    public static void storeCoords (int longit, int latit)
    {
    	myLong = longit;
    	myLat = latit;
    	
    	myDBHelper.open();
    	myDBHelper.addPosition(new Date().getTime(), longit, latit);
    	myDBHelper.close();
    }
    
    public void setCoords(int longit, int latit)
    {
    	storeCoords(longit, latit);
    	
        MapView myMapView = (MapView)findViewById(R.id.myMapView);
        MapController myMapCtrl = (MapController)myMapView.getController();
  
        GeoPoint gp = new GeoPoint(myLong, myLat);

        myMapCtrl.setCenter(gp);

		TextView myTView = (TextView)findViewById(R.id.TextView01);
		
        myTView.setText(myLat+" "+myLong);
    }
    
    public void doLogNow(View myView)
    {
		int lat=myLat, longit = myLong;
		LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
				
		Location location = locMan.getLastKnownLocation(locMan.getBestProvider(criteria,true));
		
		if (location != null)
		{
			lat = (int)(location.getLatitude()*1e6);
			longit = (int)(location.getLongitude()*1e6);
		}
		
		setCoords(longit, lat);
    	
    }
    
    @Override
    protected void onStart()
    {
    	super.onStart();
    	Toast.makeText(getApplicationContext(), "Welcome, master", Toast.LENGTH_LONG).show();
    	
    	MySettings.load();
    	
		TextView myTView = (TextView)findViewById(R.id.TextView01);
		
		myTView.setText("Interval="+MySettings.GPSPollInterval+" Distance="+MySettings.MinDistanceInterval);

    }
    
    @Override
    protected boolean isRouteDisplayed() {
    	return false;
    }
   
    @SuppressWarnings("static-access")
	public void doStartLogging(View button)
    {
    	// Get a damned GPS!

		LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    	if ( !locMan.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) 
		{
    	    	Toast.makeText(getApplicationContext(), "You need to turn on GPS...", Toast.LENGTH_LONG).show();
    	        final ComponentName toLaunch = new ComponentName("com.android.settings","com.android.settings.SecuritySettings");
    	        final Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    	        intent.addCategory(Intent.CATEGORY_LAUNCHER);
    	        intent.setComponent(toLaunch);
    	        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	        startActivityForResult(intent, 0);
    	    }
    	
    	locMan.requestLocationUpdates(locMan.GPS_PROVIDER, MySettings.GPSPollInterval, MySettings.MinDistanceInterval, myGpsLog);
    	Toast.makeText(getApplicationContext(), "Update starts!", Toast.LENGTH_LONG).show();
    }

	public void doUpload(View button)
    {
    	String xmlFile = "coords.gpx";
    	
    	File root = Environment.getExternalStorageDirectory();
    	File gpxFile = new File(root, xmlFile);
    	
    	 
    	try {
        	FileWriter gpxwriter = new FileWriter(gpxFile);
            BufferedWriter out = new BufferedWriter(gpxwriter);
    		myDBHelper.dump(out);

			
			Toast.makeText(getApplicationContext(), "Fatto, lunghezza:", Toast.LENGTH_LONG).show();

			out.close();
    	} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		// Now the real upload...
		try {
			//new HTTPFileUploader("http://192.168.0.100/index.php", "", new FileInputStream(gpxFile));
			new HTTPFileUploader("http://www.fanfilms.it/andro/index3.php", "", new FileInputStream(gpxFile));			
		} catch (FileNotFoundException e) {
			Log.i("evi", "No input file found");
		}
		
    	/*Intent sendIntent = new Intent(Intent.ACTION_SEND); 
    	sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Your GPX File, sir"); 
    	sendIntent.putExtra(Intent.EXTRA_EMAIL, "evirant@gmail.com");
    	sendIntent.putExtra(Intent.EXTRA_STREAM, "file://"+xmlFile); 
    	sendIntent.setType("application/xml");
    	startActivity(Intent.createChooser(sendIntent, "Email file"));*/
    }
    
    public void doConfig(View button)
    {
    	// Launching the preferences
    	Intent startPref = new Intent(getBaseContext(), Preferences.class);
    	
    	startActivity(startPref);
    }
}